"""
页面导航路径规划数据模型
"""

from datetime import datetime
from typing import List, Optional

from pydantic import BaseModel, Field, field_validator, ConfigDict, model_serializer


class AIWebApiCalling(BaseModel):
    """页面导航路径规划实体类"""
    page_id: str = Field(..., description="页面的全局唯一标识符，用于唯一标识导航路径中的每个页面节点")
    scene_id: str = Field(..., description="关联的业务场景唯一标识符，用于标识该导航路径所属的业务场景")
    tenant_id: str = Field(default="default", description="租户ID")
    page_name: str = Field(..., max_length=200, description="页面的中文名称，用于直观标识页面用途")
    page_tab: List[str] = Field(default_factory=list, description="页面标签页")
    function_desc_list: List[str] = Field(default_factory=list,
                                          description="页面功能的多维度描述，以数组形式存储不同角度的功能说明")
    operation_desc_list: List[str] = Field(default_factory=list,
                                           description="页面包含的操作集合描述，记录该页面可执行的操作及其用途")
    navigation_path: str = Field(..., description="页面的标准化 URL 地址，用于导航跳转，需去除 UTM 等追踪参数")
    prev_path_list: List[str] = Field(default_factory=list,
                                      description="该页面的前置路径节点 ID 集合，记录跳转到当前页面的上一页面节点 ID")
    next_path_list: List[str] = Field(default_factory=list,
                                      description="该页面的后置路径节点 ID 集合，记录从当前页面可跳转的下一页面节点 ID")
    mcp_list: Optional[List[str]] = Field(default_factory=list, description="MCP工具列表，记录与该页面相关的MCP工具列表")
    is_deleted: int = Field(default=0, description="删除标记：0-未删除,1-已删除")
    created_by: str = Field(..., max_length=50, description="记录创建该导航路径规划数据的用户标识或用户名")
    created_at: datetime = Field(..., description="记录导航路径规划数据的创建时间")
    updated_by: Optional[str] = Field(None, max_length=50,
                                      description="记录最后修改该导航路径规划数据的用户标识或用户名")
    updated_at: Optional[datetime] = Field(None, description="记录导航路径规划数据的最后修改时间")

    model_config = ConfigDict(from_attributes=True)

    @model_serializer
    def serialize_model(self):
        """自定义序列化器"""
        data = self.__dict__.copy()
        if 'created_at' in data and data['created_at']:
            data['created_at'] = data['created_at'].isoformat()
        if 'updated_at' in data and data['updated_at']:
            data['updated_at'] = data['updated_at'].isoformat()
        return data

    @field_validator('page_id', 'scene_id')
    @classmethod
    def validate_uuid_format(cls, v):
        """验证UUID格式"""
        import re
        uuid_pattern = r'^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'
        if not re.match(uuid_pattern, v, re.IGNORECASE):
            raise ValueError('ID格式不正确，应为标准UUID格式')
        return v

    @field_validator('navigation_path')
    @classmethod
    def validate_navigation_path(cls, v):
        """验证导航路径格式"""
        if not v.startswith(('http://', 'https://', '/')):
            raise ValueError('导航路径应为有效的URL地址')
        return v

    @field_validator('is_deleted')
    @classmethod
    def validate_is_deleted(cls, v):
        """验证删除标记"""
        if v not in [0, 1]:
            raise ValueError('删除标记只能是0或1')
        return v

    @field_validator('page_tab', 'function_desc_list', 'operation_desc_list')
    @classmethod
    def validate_desc_lists(cls, v):
        """验证描述列表不为空字符串"""
        if v:
            cleaned_list = [item.strip() for item in v if item.strip()]
            return cleaned_list
        return v

    @field_validator('prev_path_list', 'next_path_list')
    @classmethod
    def validate_path_lists(cls, v):
        """验证路径ID列表格式"""
        if v:
            import re
            uuid_pattern = r'^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'
            for path_id in v:
                if not re.match(uuid_pattern, path_id, re.IGNORECASE):
                    raise ValueError(f'路径ID格式不正确，应为标准UUID格式: {path_id}')
        return v


class AIWebApiCallingCreate(BaseModel):
    """创建页面导航路径规划请求模型"""
    scene_id: str = Field(..., description="关联的业务场景唯一标识符")
    tenant_id: str = Field(default="default", description="租户ID")
    page_name: str = Field(..., max_length=200, description="页面的中文名称")
    page_tab: List[str] = Field(default_factory=list, description="页面标签页")
    function_desc_list: List[str] = Field(default_factory=list, description="页面功能的多维度描述")
    operation_desc_list: List[str] = Field(default_factory=list, description="页面包含的操作集合描述")
    navigation_path: str = Field(..., description="页面的标准化 URL 地址")
    prev_path_list: List[str] = Field(default_factory=list, description="该页面的前置路径节点 ID 集合")
    next_path_list: List[str] = Field(default_factory=list, description="该页面的后置路径节点 ID 集合")
    mcp_list: Optional[List[str]] = Field(default_factory=list, description="MCP工具列表，记录与该页面相关的MCP工具列表")
    created_by: str = Field(..., max_length=50, description="创建者")

    @field_validator('scene_id')
    @classmethod
    def validate_uuid_format(cls, v):
        """验证UUID格式"""
        import re
        uuid_pattern = r'^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'
        if not re.match(uuid_pattern, v, re.IGNORECASE):
            raise ValueError('场景ID格式不正确，应为标准UUID格式')
        return v

    @field_validator('navigation_path')
    @classmethod
    def validate_navigation_path(cls, v):
        """验证导航路径格式"""
        if not v.startswith(('http://', 'https://', '/')):
            raise ValueError('导航路径应为有效的URL地址')
        return v

    @field_validator('page_tab', 'function_desc_list', 'operation_desc_list')
    @classmethod
    def validate_desc_lists(cls, v):
        """验证描述列表不为空字符串"""
        if v:
            cleaned_list = [item.strip() for item in v if item.strip()]
            return cleaned_list
        return v

    @field_validator('prev_path_list', 'next_path_list')
    @classmethod
    def validate_path_lists(cls, v):
        """验证路径ID列表格式"""
        if v:
            import re
            uuid_pattern = r'^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'
            for path_id in v:
                if not re.match(uuid_pattern, path_id, re.IGNORECASE):
                    raise ValueError(f'路径ID格式不正确，应为标准UUID格式: {path_id}')
        return v


class AIWebApiCallingUpdate(BaseModel):
    """更新页面导航路径规划请求模型"""
    page_name: Optional[str] = Field(None, max_length=200, description="页面的中文名称")
    page_tab: Optional[List[str]] = Field(None, description="页面标签页")
    function_desc_list: Optional[List[str]] = Field(None, description="页面功能的多维度描述")
    operation_desc_list: Optional[List[str]] = Field(None, description="页面包含的操作集合描述")
    navigation_path: Optional[str] = Field(None, description="页面的标准化 URL 地址")
    prev_path_list: Optional[List[str]] = Field(None, description="该页面的前置路径节点 ID 集合")
    next_path_list: Optional[List[str]] = Field(None, description="该页面的后置路径节点 ID 集合")
    mcp_list: Optional[List[str]] = Field(None, description="MCP工具列表，记录与该页面相关的MCP工具列表")
    updated_by: str = Field(..., max_length=50, description="更新者")

    @field_validator('navigation_path')
    @classmethod
    def validate_navigation_path(cls, v):
        """验证导航路径格式"""
        if v is not None and not v.startswith(('http://', 'https://', '/')):
            raise ValueError('导航路径应为有效的URL地址')
        return v

    @field_validator('page_tab', 'function_desc_list', 'operation_desc_list')
    @classmethod
    def validate_desc_lists(cls, v):
        """验证描述列表不为空字符串"""
        if v:
            cleaned_list = [item.strip() for item in v if item.strip()]
            return cleaned_list
        return v

    @field_validator('prev_path_list', 'next_path_list')
    @classmethod
    def validate_path_lists(cls, v):
        """验证路径ID列表格式"""
        if v:
            import re
            uuid_pattern = r'^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'
            for path_id in v:
                if not re.match(uuid_pattern, path_id, re.IGNORECASE):
                    raise ValueError(f'路径ID格式不正确，应为标准UUID格式: {path_id}')
        return v


class AIWebApiCallingResponse(BaseModel):
    """页面导航路径规划响应模型"""
    page_id: str
    scene_id: str
    tenant_id: str
    page_name: str
    page_tab: List[str]
    function_desc_list: List[str]
    operation_desc_list: List[str]
    navigation_path: str
    prev_path_list: List[str]
    next_path_list: List[str]
    mcp_list: Optional[List[str]]
    is_deleted: int
    created_by: str
    created_at: datetime
    updated_by: Optional[str]
    updated_at: Optional[datetime]

    model_config = ConfigDict(from_attributes=True)


class AIWebApiCallingQueryParams(BaseModel):
    """页面导航路径规划查询参数"""
    scene_id: Optional[str] = Field(None, description="场景ID筛选")
    tenant_id: Optional[str] = Field(None, description="租户ID筛选")
    page_name: Optional[str] = Field(None, description="页面名称模糊查询")
    navigation_path: Optional[str] = Field(None, description="导航路径模糊查询")
    created_by: Optional[str] = Field(None, description="创建者筛选")
    is_deleted: int = Field(default=0, description="删除标记：0-未删除,1-已删除")


class AIWebApiCallingListResponse(BaseModel):
    """页面导航路径规划列表响应模型"""
    total: int = Field(..., description="总数量")
    items: List[AIWebApiCallingResponse] = Field(..., description="页面导航路径规划列表")


class AIWebApiCallingPathUpdate(BaseModel):
    """页面路径更新模型"""
    prev_path_list: Optional[List[str]] = Field(None, description="前置路径节点 ID 集合")
    next_path_list: Optional[List[str]] = Field(None, description="后置路径节点 ID 集合")
    updated_by: str = Field(..., max_length=50, description="更新者")

    @field_validator('prev_path_list', 'next_path_list')
    @classmethod
    def validate_path_lists(cls, v):
        """验证路径ID列表格式"""
        if v:
            import re
            uuid_pattern = r'^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'
            for path_id in v:
                if not re.match(uuid_pattern, path_id, re.IGNORECASE):
                    raise ValueError(f'路径ID格式不正确，应为标准UUID格式: {path_id}')
        return v
